package com.example.rg1contactapp;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

import androidx.annotation.Nullable;

import java.util.ArrayList;

public class ContactDBHelper extends SQLiteOpenHelper
{
    public ContactDBHelper(@Nullable Context context) {
        super(context, "contact.db", null, 1);
    }

    @Override
    public void onCreate(SQLiteDatabase sqLiteDatabase) {
        sqLiteDatabase.execSQL("CREATE TABLE information(_id INTEGER PRIMARY KEY AUTOINCREMENT, name VARCHAR(20), phone VARCHAR(50))");
    }

    @Override
    public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {

    }

    public long insert(String name,String phone)
    {
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put("name", name);
        values.put("phone", phone);
        long count = db.insert("information",null,values);
        db.close();
        return count;
    }

    public int update(String name, String phone) {
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put("phone", phone);
        int number = db.update("information", values, " name =?", new
                String[]{name});
        db.close();
        return number;
    }

    public int delete(String name){
        SQLiteDatabase db = this.getWritableDatabase();
        int number = db.delete("information", "name=?", new String[]{name});
        db.close();
        return number;
    }

    public String queryByName(String name)
    {
        SQLiteDatabase db=this.getReadableDatabase();
        Cursor cursor=db.query("information",null,"name=?",new String[]{name},null,null,"name");
        if(cursor.getCount()==0)
        {
            cursor.close();
            db.close();
            return null;
        }
        else
        {
            cursor.moveToFirst();
            String phone=cursor.getString(2);
            cursor.close();
            db.close();
            return phone;
        }
    }

   public ArrayList<String> getAll()
   {
       SQLiteDatabase db=this.getReadableDatabase();
       Cursor cursor=db.query("information",null,null,null,null,null,"name");
       if(cursor.getCount()==0)
       {
           cursor.close();
           db.close();
           return null;
       }
       else
       {
           ArrayList<String> contacts=new ArrayList<>();
           while(cursor.moveToNext())
           {
               contacts.add("姓名："+cursor.getString(1)+"\n"+"电话："+cursor.getString(2)+"\n");
           }
           cursor.close();
           db.close();
           return contacts;
       }
   }



}
